package com.cloudcc.mobile.view.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.entity.beau.BeauRecordTypeEntity;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.mypage.adapter.RecorderAdapter;
import com.mypage.utils.UtilsShowDialog;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class RecordtypeActivity extends BaseActivity {
    @Bind(R.id.rbtn_vessel)
    LinearLayout rbtnVessel;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    public static RecordtypeActivity instance = null;
    public List<BeauRecordTypeEntity.DataBean> mxList;

    public RecorderAdapter mAdapter;
    private UtilsShowDialog showDialog;
    @Bind(R.id.btnCancel)
    ImageView btnCancel;
    @Bind(R.id.btnNext)
    Button btnNext;
    @Bind(R.id.listView)
    ListView listView;
    private String mEntityId;
    private String mType;
    private boolean mBtnBool;
    private String selectid;
    private String mNewUrl1;
    private String mNewUrlx;
    private String drlxr;
    private String drlxrurl;
    private Cursor phone , cursor;
    protected String username, usernumber;
    private String form;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_recordtype);
        instance = this;
        ButterKnife.bind(this);
        initData();
        initView();
        initListener();
        setOneCheck();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_recordtype;
    }

    @OnClick(R.id.btnCancel)
    public void btnCancel() {
        finish();
    }

    @OnClick(R.id.btnNext)
    public void btnNext() {
        nextStep();
    }

    public void initData() {
        showDialog = new UtilsShowDialog(this);
        if ("en".equals(mEns)) {
            showDialog.onShowLoadingDialog("loading...");
        } else {
            showDialog.onShowLoadingDialog("正在加载...");
        }

        mxList = (List<BeauRecordTypeEntity.DataBean>) getIntent().getSerializableExtra("JLLX");
        mNewUrl1 = getIntent().getStringExtra("MURL");
        mEntityId = getIntent().getStringExtra("mEntityId");
        drlxr = getIntent().getStringExtra("drlxr");
        username = getIntent().getStringExtra("name");
        usernumber = getIntent().getStringExtra("number");
        form = getIntent().getStringExtra("form");
        if(usernumber!=null) {
            usernumber = usernumber.replaceAll(" ","");
        }

        mAdapter = new RecorderAdapter(this, mxList);
    }

    public void initView() {
        listView.setAdapter(mAdapter);
        showDialog.onDismissLoadingDialog();
    }

    public void initListener() {
//        chckFirst();
        int y = 0;

        if(y==0) {
            cancelCH();
        }
        y++;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecorderAdapter.ViewHolder h = (RecorderAdapter.ViewHolder) view.getTag();

                selectid = mxList.get(position).getId();
                cancelCH();//单选开关，关闭就成了多选来
                if (h.checkBox.isChecked()) {
                    RecorderAdapter.getIsSelected().put(position, false);
                    btnNext.setTextColor(Color.rgb(204, 204, 204));
                    btnNext.setEnabled(false);
//                    mType = RecordtypeActivity.this.getIntent().getStringExtra("mType");
                    mBtnBool = false;
                } else {
                    RecorderAdapter.getIsSelected().put(position, true);
                    btnNext.setTextColor(Color.rgb(0, 123, 199));
                    btnNext.setEnabled(true);
//                    mType = mList.get(position).Id;
                    mBtnBool = true;
                }

                mAdapter.notifyDataSetChanged();
            }
        });
//        for (int i = 0;i<mxList.size();i++){
//            if(mType.equals(mxList.get(i).getName())){
//                mBtnBool = true;
//                NchageRecorderAdapter.getIsSelected().put(i, true);
//                btnNext.setTextColor(Color.rgb(204, 204, 204));
//                mBtnBool = false;
//            }
//        }
    }

    public void cancelCH() {
        for (int i = 0; i < mxList.size(); i++) {
            if (RecorderAdapter.getIsSelected().get(i)) {
                RecorderAdapter.getIsSelected().put(i, false);

            }

        }
    }
    public void setOneCheck(){
        for (int i = 0; i < mxList.size(); i++){
            if("true".equals(mxList.get(i).getIsdefault())) {
                RecorderAdapter.getIsSelected().put(i, true);
                selectid = mxList.get(i).getId();
            }
        }

    }

    public void chckFirst() {
        RecorderAdapter.getIsSelected().put(0, true);
        selectid = mxList.get(0).getId();
    }

    public void nextStep() {
        String ids = mType;
        String mSweb = "selectedRecordType";
        
        if("drlxr".equals(drlxr)) {
            Uri uri = ContactsContract.Contacts.CONTENT_URI;
            Intent intentx = new Intent(Intent.ACTION_PICK, uri);
            startActivityForResult(intentx,0);
        }else{
            Intent intent = new Intent(this, CloudWebViewActivity.class);
        if(usernumber!=null) {
            if(usernumber.length() == 11){
                mNewUrlx = UrlManager.getManager()
                        .addReturnUrl(mNewUrl1)+"&name="+(TextUtils.isEmpty(username)?"":username)+(mEntityId.equals("003") ? "&shouji=" : "&phone=")+usernumber+ "&selectedRecordType=" + selectid;
            }else{
                mNewUrlx = UrlManager.getManager()
                        .addReturnUrl(mNewUrl1)+"&name="+(TextUtils.isEmpty(username)?"":username)+"&dianhua="+(TextUtils.isEmpty(usernumber)?"":usernumber)+"&selectedRecordType=" + selectid;
            }
        }else {
            mNewUrlx = UrlManager.getManager()
                    .addReturnUrl(mNewUrl1)+"&selectedRecordType=" + selectid;
        }


            intent.putExtra(ExtraConstant.EXTRA_URL,mNewUrlx);

            Log.i("TAG", "sssssss" + selectid);
            intent.putExtra("daoruurl", mNewUrlx);
            WebSyncDefaultProxy.MonitorParam monitorParam = new WebSyncDefaultProxy.MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());
            intent.putExtra("form",form);
            startActivity(intent);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            // ContentProvider展示数据类似一个单个数据库表
            // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
            ContentResolver reContentResolverol = getContentResolver();
            // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
            Uri contactData = data.getData();
            // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.

            cursor = getContentResolver().query(contactData, null, null, null, null);
            if (cursor == null) {
                Toast.makeText(this,"通讯录权限未开启", Toast.LENGTH_SHORT).show();
                return;
            }
            cursor.moveToFirst();
            // 获得DATA表中的名字
            username = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            // 条件为联系人ID
            String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
            phone = reContentResolverol.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                            + contactId, null, null);
            while (phone.moveToNext()) {
                usernumber = phone
                        .getString(phone
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ","");

            }
            if(usernumber == null || usernumber.equals(" ")) {

                drlxrurl = UrlManager.getManager()
                        .addReturnUrl(mNewUrl1)+"&name="+(TextUtils.isEmpty(username)?"":username)+ "&selectedRecordType=" + selectid;
            }else {
                if(usernumber.length() == 11){
                    drlxrurl = UrlManager.getManager()
                            .addReturnUrl(mNewUrl1)+"&name="+(TextUtils.isEmpty(username)?"":username)+(mEntityId.equals("003") ? "&shouji=" : "&phone=")+usernumber+ "&selectedRecordType=" + selectid;
                }else{
                    drlxrurl = UrlManager.getManager()
                            .addReturnUrl(mNewUrl1)+"&name="+(TextUtils.isEmpty(username)?"":username)+"&dianhua="+(TextUtils.isEmpty(usernumber)?"":usernumber)+"&selectedRecordType=" + selectid;
                }
            }

            Intent intent = new Intent(this, CloudWebViewActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_URL, drlxrurl);
            intent.putExtra("daoruurl", mNewUrl1);
            WebSyncDefaultProxy.MonitorParam monitorParam = new WebSyncDefaultProxy.MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());

            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }
}
